package com.java.jiuyang.commons.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


/**
 * @ClassName: HttpUtil
 * @Description:
 * @Version: v1.0.0
 * @Author: Fu Hao
 * @Date: 2019/10/26 0026 上午 11:24
 * Modification History:
 * Date           Author      Version     Description
 * -------------------------------------------------------------
 * 2019/10/26 0026        Fu Hao      v1.0.0         创建
 */
public class HttpUtil {

    private static final Logger log = (Logger) LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 使用Get方式获取数据
     * @param url
     * @param charset
     * @return
     */
    public static String sendGet(String url) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("发送 GET 请求出现异常:",e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e2) {
                log.error("关闭流异常:",e2);
            }
        }
        return result.toString();
    }


    public static String normalizePath(String path) {
        if (!StringUtils.isEmpty(path)) {
            try {
                path = path.replaceFirst("(?=(http:|https:|ftp:))/{3,}", "/{2}");
                path = path.replaceAll("(?<!(http:|https:|ftp:))/{2,}", "/");
            } catch (Exception e) {}
        }
        return path;
    }

    public static String normalizePath1(String path) {
        if (!StringUtils.isEmpty(path)) {
            try {
                path = path.replaceAll("/{2,}", "/");
            } catch (Exception e) {}
        }
        return path;
    }
}
